# coding=utf-8
import pymysql

class DBSystem(object):

    def __init__(self):
        self.conn = pymysql.connect(host="115.159.110.13", port=3388, user="root", password="kkk@32286956", database="HuaYiSYS", charset="utf8",
                               connect_timeout=2000)
        self.cursor = self.conn.cursor()

    def get_conn(self):
        return self.conn

    def get_cursor(self):
        return self.cursor

    def isInItem(self, value): #查询不到返回False
        state = False
        try:
            self.cursor.execute("select item_value from tmp_huayi_item2 where item_value='%s'"% str(value))
            list = self.cursor.fetchone()
            if list:
                state = True
        except:
            state = False
        return state

    def isInCourse(self, value):
        state = False
        try:
            self.cursor.execute("select course_value from tmp_huayi_course2 where course_value='%s'"% str(value))
            list = self.cursor.fetchone()
            if list:
                state = True
        except:
            state = False
        return state

    def isInStudy(self, value):
        state = False
        try:
            self.cursor.execute("select study_value from tmp_huayi_study2 where study_value='%s'"% str(value))
            list = self.cursor.fetchone()
            if list:
                state = True
        except:
            state = False
        return state

    def save_item(self, value):
        if not self.isInItem(value):
            try:
                self.cursor.execute("insert into tmp_huayi_item2 (item_value) values('%s')" % str(value))
                self.conn.commit()
            except:
                raise IOError("Error: unable to save course_value")

    # def save_item(self, value):
    #     if not self.isInItem(value):
    #         cursor = self.conn.cursor()
    #         try:
    #             cursor.execute("insert into tmp_huayi_item (item_value) values('%s')" % str(value))
    #             self.conn.commit()
    #         except:
    #             raise IOError("Error: unable to save course_value")
    #         self.cursor.close()

    def save_course(self, value):
        if not self.isInCourse(value):
            try:
                self.cursor.execute("insert into tmp_huayi_course2 (course_value) values('%s')" % str(value))
                self.conn.commit()
            except:
                raise IOError("Error: unable to save course_value")



    def save_study(self, value):
        if not self.isInStudy(value):
            try:
                self.cursor.execute("insert into tmp_huayi_study2 (study_value) values('%s')" % str(value))
                self.conn.commit()
            except:
                raise IOError("Error: unable to save study_value")

    def db_close(self):
        self.cursor.close()
        self.conn.close()